<?php
namespace app\moddleware\api;

use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use think\Exception;

class CheckToken
{
    public function handle($request, \Closure $next)
    {
        // 验证 Token
        $token = $request->header('token');
        if (empty($token)) {
            return json([
                'code' => 0,
                'msg' => '请先登录',
                'data' => null
            ]);
        }
        // 验证 token 真实性
        try {
            $data = JWT::decode($token, new Key(config('zmt.jwtKey'), 'HS256'));
        } catch (SignatureInvalidException $signatureInvalidException) {
            return json([
                'code' => 0,
                'msg' => $signatureInvalidException->getMessage(),
                'data' => null
            ]);
        } catch (ExpiredException $expiredException) {
            return json([
                'code' => 0,
                'msg' => $expiredException->getMessage(),
                'data' => null
            ]);
        } catch (Exception $exception) {
            return json([
                'code' => 0,
                'msg' => $exception->getMessage(),
                'data' => null
            ]);
        }

        $request->user_id = $data->data->user_id;

        return $next($request);
    }
}
